package com.ejlchina.tool.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.adolf.androiddemo.databinding.FragmentReuseBinding
import com.ejlchina.tool.adapter.DeviceAdapterRadio
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.bean.ReuseFunctionBean
import com.ejlchina.tool.singleton.GlobalConnectObject
import com.ejlchina.tool.util.COMMAND_REUSE_GET_All_CLOSE_UPWARD
import com.ejlchina.tool.util.COMMAND_REUSE_GET_DOWNLOAD
import com.ejlchina.tool.util.COMMAND_REUSE_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_REUSE_SET_DOWNLOAD
import com.ejlchina.tool.util.COMMAND_REUSE_SET_UPWARD
import com.ejlchina.tool.util.LOG_TAG
import com.ejlchina.tool.util.bytearray.toHexString
import com.ejlchina.tool.view.GridItemDecoration
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ReuseFragment: BaseBindingFragment2<FragmentReuseBinding>() {

    private var reuseFunctionBeanRead = ReuseFunctionBean()
    private val reuseFunctionBean = ReuseFunctionBean()
    private var returnCount = 0
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        initData()
    }

    private fun initViews(){
        setHeadTitle("复用功能")
        initListeners()
    }

    private fun initData(){
        initDevices()
    }

    private fun initDevices(){
        deviceAdapter = DeviceAdapterRadio(GlobalConnectObject.getCurrentConnectDeviceList()){
            getReuseData(it)
        }
        binding.rvDevices.apply {
            adapter = deviceAdapter
            layoutManager = GridLayoutManager(requireContext(),3)
            if (itemDecorationCount == 0){
                addItemDecoration(GridItemDecoration(3,11,11))
            }
        }
    }


    private fun initListeners(){
        binding.switchAutoBreak.setOnCheckedChangeListener { _, isChecked ->
            reuseFunctionBean.autoBrokenOn = isChecked
            if (isChecked){
                binding.switchBottleCount.isChecked = false
                binding.switchBottleDeliver.isChecked = false
                binding.switchDeodorization.isChecked = false
                binding.switchLightShield.isChecked = false
            }
        }

        binding.switchBottleDeliver.setOnCheckedChangeListener { _, isChecked ->
            reuseFunctionBean.bottleDeliverOn = isChecked
            if (isChecked){
                binding.switchBottleCount.isChecked = false
                binding.switchAutoBreak.isChecked = false
                binding.switchDeodorization.isChecked = false
                binding.switchLightShield.isChecked = false
            }
        }

        binding.switchBottleCount.setOnCheckedChangeListener { _, isChecked ->
            reuseFunctionBean.bottleCountOn = isChecked
            if (isChecked){
                binding.switchAutoBreak.isChecked = false
                binding.switchBottleDeliver.isChecked = false
                binding.switchDeodorization.isChecked = false
                binding.switchLightShield.isChecked = false
            }
        }

        binding.switchDeodorization.setOnCheckedChangeListener{_, isChecked ->
            reuseFunctionBean.deodorization = isChecked
            if (isChecked){
                binding.switchAutoBreak.isChecked = false
                binding.switchBottleDeliver.isChecked = false
                binding.switchBottleCount.isChecked = false
                binding.switchLightShield.isChecked = false
            }
        }

        binding.switchLightShield.setOnCheckedChangeListener { _, isChecked ->
            reuseFunctionBean.lightShield = isChecked
            if (isChecked){
                binding.switchAutoBreak.isChecked = false
                binding.switchBottleDeliver.isChecked = false
                binding.switchDeodorization.isChecked = false
                binding.switchBottleCount.isChecked = false
            }
        }

        binding.btnConfirm.setOnClickListener {
            returnCount = 0
            setReuseOffData(deviceAdapter.getSelectDevice())
        }
    }

    override fun whenReceiveCommand(bleDevice: BleDeviceBean,command: String, dataByteArray: ByteArray) {
        super.whenReceiveCommand(bleDevice,command, dataByteArray)
        when(command){
            COMMAND_REUSE_GET_UPWARD -> {
                when(dataByteArray[0].toInt()){
                    1 -> {
                        reuseFunctionBean.autoBrokenOn = true
                        reuseFunctionBeanRead.autoBrokenOn = true
                    }
                    2 -> {
                        reuseFunctionBean.bottleDeliverOn = true
                        reuseFunctionBeanRead.bottleDeliverOn = true
                    }
                    3 -> {
                        reuseFunctionBean.bottleCountOn = true
                        reuseFunctionBeanRead.bottleCountOn = true
                    }

                    4 -> {
                        reuseFunctionBean.deodorization = true
                        reuseFunctionBeanRead.deodorization = true
                    }

                    5 -> {
                        reuseFunctionBean.lightShield = true
                        reuseFunctionBeanRead.lightShield = true
                    }
                }
                setUIState()
                dismissLoading()
            }

            COMMAND_REUSE_GET_All_CLOSE_UPWARD -> {
                reuseFunctionBeanRead.closeReuseFunction()
                reuseFunctionBean.closeReuseFunction()
                setUIState()
                dismissLoading()
            }

            COMMAND_REUSE_SET_UPWARD -> {
                ++returnCount
                Log.i(LOG_TAG,"*************${returnCount}")
                if (returnCount == 5){
                    dismissLoading()
                    reuseFunctionBeanRead = reuseFunctionBean.copy()
                    setResultToast(dataByteArray[dataByteArray.size - 1].toInt())
                }
            }
        }
    }

    private fun setUIState(){
        binding.switchAutoBreak.isChecked = reuseFunctionBean.autoBrokenOn
        binding.switchBottleCount.isChecked = reuseFunctionBean.bottleCountOn
        binding.switchBottleDeliver.isChecked = reuseFunctionBean.bottleDeliverOn
        binding.switchDeodorization.isChecked = reuseFunctionBean.deodorization
        binding.switchLightShield.isChecked = reuseFunctionBean.lightShield
    }


    private fun getReuseData(bleDevice: BleDeviceBean){
        getCommandData(bleDevice, COMMAND_REUSE_GET_DOWNLOAD)
    }

    private fun setReuseOffData(bleDevice: BleDeviceBean) {

        viewLifecycleOwner.lifecycleScope.launch {
            setCommandData(
                bleDevice,
                COMMAND_REUSE_SET_DOWNLOAD,
                byteArrayOf(1.toByte(), if (reuseFunctionBean.autoBrokenOn) 1.toByte() else 0.toByte()).toHexString(false)
            )

            delay(400)

            setCommandData(
                bleDevice,
                COMMAND_REUSE_SET_DOWNLOAD,
                byteArrayOf(3.toByte(), if (reuseFunctionBean.bottleCountOn) 1.toByte() else 0.toByte()).toHexString(false)
            )

            delay(400)

            setCommandData(
                bleDevice,
                COMMAND_REUSE_SET_DOWNLOAD,
                byteArrayOf(2.toByte(), if (reuseFunctionBean.bottleDeliverOn) 1.toByte() else 0.toByte()).toHexString(false)
            )

            delay(400)

            setCommandData(
                bleDevice,
                COMMAND_REUSE_SET_DOWNLOAD,
                byteArrayOf(4.toByte(), if (reuseFunctionBean.deodorization) 1.toByte() else 0.toByte()).toHexString(false)
            )

            delay(400)
            setCommandData(
                bleDevice,
                COMMAND_REUSE_SET_DOWNLOAD,
                byteArrayOf(5.toByte(), if (reuseFunctionBean.lightShield) 1.toByte() else 0.toByte()).toHexString(false)
            )
        }
    }



    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentReuseBinding {
        return FragmentReuseBinding.inflate(inflater,container,true)
    }

}